<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, deleteRentAPI, getEnterpriseDetailAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';


const outRent = (row:Datum)=>{
  ElMessageBox.confirm('退租后不可撤回，确认退租吗？','温馨提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(async ()=>{
    // 1.发送请求，更新后端合同状态
    await outRentAPI(row.id)
    row.status = 3
    // 2 更新前端合同状态，退租按钮变禁用
    ElMessage.success('退租成功！')
  }).catch(()=>{

  })
    
  
}
// 编辑企业 1.携带参数跳转到编辑页
const router = useRouter()
const editRent = (id:string) =>{
  router.push({
    path:'/exterpriseAdd',
    query:{
      id
    }
  })
}
// 自定义的类型，用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList:Datum[]
}

// 1.获取企业列表

const params = ref<EnterpriseListParams>({
  page:1,
  pageSize:10,
  name:''
})
const list = ref<EnterpriseWithRent[]> ([])
const total = ref(0)
const getExterpriseList = async() =>{
  const res = await getEnterpriseListAPI(params.value)
  list.value=res.data.rows.map(item=>({
    ...item,
    rentList:[] //合同列表默认值，用于嵌套表格渲染
  }))
  total.value= res.data.total
}

getExterpriseList()

// 搜索业务

const onSearch = () =>{
  // 搜索时，由于条件变了。返回的数据不一样，所以需要重置页码
  params.value.page = 1
  // 重新请求数据
  getExterpriseList()
}


// 添加合同
const rentDialogVisible = ref(false)  //是否显示合同

const buildList = ref<RentBuilding[]>([])
// 打开添加合同窗口
const addRent = async(id:number)=>{
  rentDialogVisible.value = true
  // 打开弹窗时调用接口，获取下拉菜单
  const res = await getRentBuildListAPI()
  buildList.value = res.data
  // 保存企业id，用于添加合同
  rentForm.value.enterpriseId = id
}
// 点击添加合同同弹窗的确认按钮
const addRentConfirm = async () =>{
  try{
    // 1.表单校验
    await addFormRef.value?.validate()
    // 2.提交表单数据给后端
    await createRentAPI(rentForm.value)
    // 3.轻提示
    ElMessage.success('添加成功')
    // 4.关闭弹窗
    closeRent()
  }catch{

  }
}


// 表单数据默认值
const initRentForm =()=>{
  // 每次调用都返回一个新对象
  return {
    
  buildingId:undefined,
  startTime:'',
  endTime:'',
  contractUrl:'',
  contractId:undefined,
  type:0,
  enterpriseId:undefined
  }
}
// 添加合同 表单数据
const rentForm = ref<RentParams>(initRentForm())

// 关闭合同添加窗口
const closeRent = ()=>{
  // 关闭弹窗
  rentDialogVisible.value = false
  // 重置表单校验
  addFormRef.value?.resetFields()
  // 重置日期选择器数据
  timeArr.value=[]
  // 重置提交给后端的表单数据
  rentForm.value={
  buildingId:undefined,
  startTime:'',
  endTime:'',
  contractUrl:'',
  contractId:undefined,
  type:0,
  enterpriseId:undefined
  }
}

// 校验规则

const rentRules = ref<FormRules<RentParams>>({
  buildingId:[
    {required:true,message:'请选择楼宇',trigger:'blur'}
  ],
  endTime:[
    {required:true,message:'请选择租赁日期',trigger:'blur'}
  ],
  contractId:[
    {required:true,message:'请上传合同文件'}
  ]
})

// 时间选择器 监听时间变化
const timeArr = ref<string[]>([])

watch (timeArr,(val)=>{
  if(val){
    rentForm.value.startTime = val [0]
    rentForm.value.endTime = val[1]
  }else{
    rentForm.value.startTime = ''
    rentForm.value.endTime = ''
  }
},{deep:true})
// 通过disabled 函数，来设置禁用掉的日期
const disabledDate = (time:Date)=>{
  // 不能小于今日日期,包含今天 (1000 * 60  *60 *24)  减掉1天的毫秒数
  return time.getTime() < Date.now() -1000 * 60  *60 *24
}

const addFormRef = ref<FormInstance>()
// 上传合同文件
const onUploadRequest = async (options:UploadRequestOptions)=>{
  // 1.准备FormData对象
  const fd = new FormData()
  fd.append('file',options.file)
  fd.append('type','contract')
  // 2.发送请求
  const res = await uploadAPI(fd)

  // 3.保存合同附件url和id，用于添加合同
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id

  // 4.主动触发校验(如果通过校验，会清除错误信息)
  addFormRef.value?.validateField('contractId')

  // 5.return 后端返回的数据,保存到response中
  return res.data
}
// 上传前校验大小
const beforeUpload = (rawFile:UploadRawFile)=>{
  // 允许的文件大小
  const allowSize = 5 * 1024 * 1024
  // 检测文件大小
  if(rawFile.size > allowSize){
    ElMessage.error('文件过大，请上传5M以下的文件')
    return false
  }
  return true
}

// 删除合同 
const deleteRent = async(rentRow:Datum,enterPriseRow:EnterpriseWithRent) =>{
  ElMessageBox.confirm('是否确认删除当前合同？','温馨提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(async ()=>{
    // 
    await deleteRentAPI(rentRow.id)
    // 
    enterPriseRow.rentList = enterPriseRow.rentList.filter(item => item.id !== rentRow.id)
    // 
    ElMessage.success('删除成功')
    
  }).catch(()=>{

  })
}

// 删除合同文件
const removeUpload = () =>{
  // 清空数据
  rentForm.value.contractUrl=''
  rentForm.value.contractId = undefined
  // 触发校验
  addFormRef.value?.validateField('contractId')
}

// 展开行时触发
const onExpandChange = async (row:EnterpriseWithRent) =>{
  
  const res = await getRentListAPI(row.id)
  console.log('当前行展开',row.id)
  // 把请求回来的数据，直接保存到当前行的企业信息中
  row.rentList = res.data
}

// 删除企业

const onDeleteEnterprise =  (id:string) =>{
  ElMessageBox.confirm('确定删除该企业吗？','温馨提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消'
  }).then(async()=>{
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功！')
    getExterpriseList()
  }).catch(()=>{})
}

</script>


<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" class="search-main" v-model="params.name"/>
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>  
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id"> 
        <!-- 新增：展开部分 -->
            <el-table-column type="expand">
              <template #default="{ row }">
                <el-table :data="row.rentList">
                  <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
                  <el-table-column label="租赁起始时间" prop="startTime" />
                  <el-table-column label="合同状态" prop="status">
                    <template v-slot="{ row }">
                      <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                      <el-tag v-else-if="row.status === 1 " type="success">生效中</el-tag>
                      <el-tag v-else-if="row.status === 2 " type="info">已到期</el-tag>
                      <el-tag v-else-if="row.status === 3 " type="danger">已退租</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="280">
                    <template #default="{ row: rentRow }">
                      <el-button size="small" type="primary" link>续租</el-button>
                      <el-button size="small" type="primary" link :disabled="rentRow.status === 3 " @click="outRent(rentRow)">退租</el-button>
                      <el-button size="small" type="primary" link :disabled="rentRow.status !== 3" @click="deleteRent(rentRow,row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name"/>
        <el-table-column label="联系人" prop="contact"/>
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="300">
          <template v-slot="{row}">
            <el-button size="small" type="primary" link @click="addRent(row.id)" >添加合同</el-button>
           
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseAdd/${row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" link @click="onDeleteEnterprise(row.id)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="total" layout="total, prev, pager, next, sizes, jumper"
      :page-sizes="[2,5,10,20,100]"
      v-model:page-size="params.pageSize"
      v-model:current-page="params.page"
      @change="getExterpriseList()"
      />
    </div>
    <el-dialog title="添加合同" v-model="rentDialogVisible" width="580px" @close="closeRent">
  <!-- 使用具名插槽包裹整个对话框内容 -->
  <template #default>
    <!-- 表单区域 -->
    <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
      <el-form-item label="租赁楼宇" prop="buildingId">
        <el-select placeholder="请选择" v-model="rentForm.buildingId" clearable>
          <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="租赁起止日期" prop="endTime">
        <el-date-picker v-model="timeArr" type="daterange"
          range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD"
          :disabled-date="disabledDate">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="租赁合同" prop="contractId">
        <el-upload accept=".doc,.pdf" :http-request="onUploadRequest" @remove="removeUpload" :before-upload="beforeUpload">
          <el-button type="primary" plain>上传合同文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
          </template>
        </el-upload>
      </el-form-item>
      {{ timeArr }}
      {{ rentForm }}
    </el-form>
  </template>
  <template #footer>
    <el-button @click="closeRent">取消</el-button>
    <el-button type="primary" @click="addRentConfirm">确定</el-button>
  </template>
</el-dialog>
  </div>
  {{ params }}
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>